package com.egreen.order.aspect;

import com.egreen.order.utils.OrderCountRedisUtil;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author cloudJiang
 * @date 2022/9/20 21:54
 */
@Aspect
@Component
public class OrderAspect {
    @Autowired
    OrderCountRedisUtil countUtil;
    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    //定义三个切入点

    @Pointcut("execution(void com.egreen.order.service.impl.OrderServiceImpl.commitOrder(..))")
    private void commitPointCut() {

    }

    @Pointcut("execution(void com.egreen.order.service.impl.OrderServiceImpl.commitErrorOrder(..))")
    private void errorPointCut() {

    }

    @Pointcut("execution(void com.egreen.order.service.impl.OrderServiceImpl.overOrder(..))")
    private void overPointCut() {

    }


    @After("commitPointCut()")
    public void orderCommitCount() {
        String date = formatter.format(new Date(System.currentTimeMillis()));
        String operate = "running";

        //判断总记录是否存在
        if (!countUtil.existAll()) {
            countUtil.createAll();
        } else {
            //添加总记录
            countUtil.addAll();
        }
        //判断当天记录是否存在
        if (!countUtil.existDay(operate, date)) {
            countUtil.createDay(operate, date);
        } else {
            //添加该操作的当天记录
            countUtil.addDay(operate, date);
        }
        if (!countUtil.existAll(date)) {
            countUtil.createAll(date);
        } else {
            //添加当天总记录
            countUtil.addAll(date);
        }
    }

    @After("errorPointCut()")
    public void orderErrorCount() {
        String date = formatter.format(new Date(System.currentTimeMillis()));
        String operate = "running";

        //减少一个正在运行订单
        countUtil.subDay(operate, date);
    }

    @After("overPointCut()")
    public void orderOverCount() {
        String date = formatter.format(new Date(System.currentTimeMillis()));
        String operateR = "running";
        String operateO = "over";

        //减少一个正在运行订单，增加一个已完成订单
        countUtil.subDay(operateR, date);
        countUtil.addDay(operateO, date);
    }

}
